<?php


namespace app\controller\admin;


use app\model\AdminUnlockRecord;
use app\util\ExcelHandle;
use app\util\ReturnCode;
use think\Response;

class DormitoryRecord extends Base
{
    public function index(): Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $phone = $this->request->get('phone', '');
        $student_name = $this->request->get('student_name', '');
        $student_no = $this->request->get('student_no', '');
        $dormitory_id = $this->request->get('dormitory_id', null);
        $student_dormitory_id = $this->request->get('student_dormitory_id', null);
        $date = $this->request->get('date/a');
        $sortKey = $this->request->get('sortKey', 'create_time');
        $order = $this->request->get('order', 'DESC');
        $where = [];

        $obj = (new AdminUnlockRecord())->alias('AdminUnlockRecord');

        if ($school_id) {
            array_push($where, ['AdminUnlockRecord.school_id', '=', $school_id]);
        }
        if ($dormitory_id) {
            array_push($where, ['AdminUnlockRecord.dormitory_id', '=', $dormitory_id]);
        }
        if ($student_dormitory_id) {
            array_push($where, ['AdminUnlockRecord.student_dormitory_id', '=', $student_dormitory_id]);
        }
        if ($phone) {
            $obj = $obj->hasWhere('staff', function ($query) use ($phone) {
                $query->where('phone', 'like', '%' . $phone . '%');
            });
        }
        if ($student_no) {
            $obj = $obj->hasWhere('staff', function ($query) use ($student_no) {
                $query->where('student_no', 'like', '%' . $student_no . '%');
            });
        }
        if ($student_name) {
            $obj = $obj->hasWhere('staff', function ($query) use ($student_name) {
                $query->where('name', 'like', '%' . $student_name . '%');
            });
        }
        if ($date && is_array($date)){
            $start_date = $date[0] ? $date[0] : '';
            $end_date = $date[1] ? $date[1] : '';
            if ($start_date){
                array_push($where, ['AdminUnlockRecord.create_time', '>=', strtotime($start_date)]);
            }
            if ($end_date){
                array_push($where, ['AdminUnlockRecord.create_time', '<=', strtotime($end_date)]);
            }
        }
        $listObj = $obj->where($where)->with(['staff','school','dormitory','student'])
            ->append(['unlock_type_text','unlock_status_text'])
            ->order('AdminUnlockRecord.'.$sortKey, $order)
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();

        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total'],
        ]);
    }

    /**
     * @func download
     * @desc 导出文件
     * @return \think\Response
     * @Time: 2021/12/17 11:18
     */
    public function download(): Response  {
        $titles = [['id' => '序号'],['school_name' => '所属学校'],['dormitory_name'=>'宿舍楼名称'],['student_dormitory_name'=>'宿舍号'],['staff_name'=>'姓名'],['staff_rule' => '操作人身份'],['unlock_type_text' => '开锁方式'],['create_time' => '开锁时间']];

        $school_id = $this->request->get('school_id');
        $phone = $this->request->get('phone', '');
        $student_no = $this->request->get('student_no', '');
        $dormitory_id = $this->request->get('dormitory_id', null);
        $student_dormitory_id = $this->request->get('student_dormitory_id', null);
        $date = $this->request->get('date');

        try {
            $obj = (new AdminUnlockRecord())->alias('AdminUnlockRecord');
            $where = [];

            if ($school_id) {
                array_push($where, ['AdminUnlockRecord.school_id', '=', $school_id]);
            }
            if ($dormitory_id) {
                array_push($where, ['AdminUnlockRecord.dormitory_id', '=', $dormitory_id]);
            }
            if ($student_dormitory_id) {
                array_push($where, ['AdminUnlockRecord.student_dormitory_id', '=', $student_dormitory_id]);
            }
            if ($phone) {
                $obj = $obj->hasWhere('staff', function ($query) use ($phone) {
                    $query->where('phone', 'like', '%' . $phone . '%');
                });
            }
            if ($student_no) {
                $obj = $obj->hasWhere('staff', function ($query) use ($student_no) {
                    $query->where('student_no', 'like', '%' . $student_no . '%');
                });
            }
            if ($date){
                $date = explode(',', $date);
                $start_date = isset($date[0]) ? $date[0] : '';
                $end_date = isset($date[1]) ? $date[1] : '';
                if ($start_date){
                    array_push($where, ['AdminUnlockRecord.create_time', '>=', strtotime($start_date)]);
                }
                if ($end_date){
                    array_push($where, ['AdminUnlockRecord.create_time', '<=', strtotime($end_date)]);
                }
            }

            $exportData = [];
            $len = 1;
            $page = 1;    // 页面
            $pageSize = 1000;    //每页条数
            while(
                $listObj = $obj->where($where)->with(['staff','school','dormitory','student'])
                    ->append(['unlock_type_text'])
                    ->order('AdminUnlockRecord.create_time', 'DESC')
                    ->page($page)->limit($pageSize)->select()->toArray()
            )
            {
                foreach ($listObj as $datum) {
                    $datum['student_dormitory_name'] .= "\t";
                    $datum['staff_name'] .= "\t";
                    $newItem = array_merge(['id' => $len],$datum);
                    array_push($exportData, $newItem);
                    $len++;
                }
                $page++;
                if ($page > 20) {
                    break;
                }
            }

//            $listObj = $obj->where($where)->with(['staff','school','dormitory','student'])
//                ->append(['unlock_type_text'])
//                ->order('AdminUnlockRecord.create_time', 'DESC')
//                ->select()->toArray();
//
//            $exportData = [];
//            $len = 1;
//            foreach ($listObj as $datum) {
//                $datum['student_dormitory_name'] .= "\t";
//                $datum['staff_name'] .= "\t";
//                $newItem = array_merge(['id' => $len],$datum);
//                array_push($exportData, $newItem);
//                $len++;
//            }

            ExcelHandle::downLoadExcel('宿舍开锁信息' . date('YmdHi'), $titles, $exportData);
        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }
}